<template>
	<view class="content">
		<view style="z-index: 100;position: sticky;top :0;">
			<z-tabs scroll-count="1" bg-color="transparent"
				:active-style="{background: '#CCE2FF',borderRadius: '28rpx',fontWeight: '500',fontSize: '28rpx',color: '#2F80ED',padding: '8rpx 16rpx'}"
				bar-width="0" bar-height="0" :list="tabs1" class="box_2_tabs" @change="onChange">
				<template slot="right">
					<view class="selectMore uni-flex uni-justify-between uni-align-center" @click="openSelectService">
						<text class="text-group_10">筛选</text>
						<image class="more_img" referrerpolicy="no-referrer" :src="`${$ImgBaseUrl}select_gray.png`" />
					</view>
				</template>
			</z-tabs>
		</view>
		<z-paging ref="pagingRef" v-if="initialized" v-model="dataList" @query="queryList" :fixed="false"
			:refresher-enabled="!props.disableRefresh">
			<view class="item uni-flex uni-justify-between" v-for="(item, index) in dataList" :key="index"
				@click="itemClick(item)">
				<image class="left_img" referrerpolicy="no-referrer" :src="item.baseSmallImgUrl" />
				<view class="uni-flex-item uni-flex uni-column uni-justify-between">
					<view class="title">{{item.itemName}}</view>
					<view class="desc">{{item.itemRemark}}</view>
					<view class="uni-flex uni-justify-between uni-align-center">
						<view>
							<text class="price1">¥</text>
							<text class="price2">{{item.paramMinPrice}}-{{item.paramMaxPrice}}</text>
							<text class="text3">/{{item.paramPriceUnit}}</text>
						</view>
						<uni-icons type="right" size="12" color="#999999"></uni-icons>
					</view>
				</view>
			</view>
			<template #empty>
				<view>暂无数据</view>
			</template>
		</z-paging>
	</view>
</template>

<script setup>
	import {
		ref,
		watch,
		nextTick,
		reactive,
		toRefs,
		onMounted,
		onUnmounted,
	} from "vue";
	import {
		querySeviceList,
		getSevItemList
	} from "@/api/home.js";
	import {
		getAreaid
	} from "@/common/util.js";

	const state = reactive({
		current1: 0,
		currentGroupId: null, // 存储二级类目ID
		currentServiceId: null, // 存储一级类目ID
		currentAreaId: "",
		itemIds: [],
		isReloading: false // 防止重复加载的标志
	});

	const props = defineProps({
		tabIndex: {
			type: Number,
			default: 0
		},
		currentIndex: {
			type: Number,
			default: 0
		},
		serviceTabs: {
			type: Array,
			default: () => []
		},
		disableRefresh: {
			type: Boolean,
			default: false
		},
		itemIdsArr: { // 新增：接收itemIds数组
			type: Array,
			default: () => []
		}
	});

	const tabs1 = ref([]);
	const dataList = ref([]);
	const pagingRef = ref(null);
	const initialized = ref(false);

	const handleAreaChange = async (data) => {
		if (!data?.areaId) {
			console.error('未获取到有效的areaId:', data);
			return;
		}

		state.currentAreaId = data.areaId;
		console.log('服务列表组件接收到的areaId:', state.currentAreaId);

		if (pagingRef.value) {
			await nextTick();
			pagingRef.value.reload();
		} else {
			console.warn('z-paging组件未初始化完成，延迟刷新');
			setTimeout(() => {
				pagingRef.value?.reload();
			}, 300);
		}
	};

	watch(() => props.serviceTabs, (newVal, oldVal) => {
		// 只有当serviceTabs真正发生变化时才处理
		if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
			tabs1.value = newVal;
			if (newVal.length > 0) {
				// 处理ID格式，如 "37-24" 分割为 groupId=24(二级类目ID), serviceId=37(一级类目ID)
				const [serviceId, groupId] = newVal[0].id.split('-');
				state.currentServiceId = Number(serviceId); // 一级类目ID
				state.currentGroupId = Number(groupId); // 二级类目ID
				// 只有当当前标签页是激活状态时才刷新
				// if (props.currentIndex === props.tabIndex) {
				// 	reload();
				// }
			}
		}
	}, {
		immediate: true,
		deep: true
	});

	const onChange = (e) => {
		const selectedTab = tabs1.value[e];
		if (selectedTab && selectedTab.id) {
			// 处理ID格式，如 "37-24" 分割为 groupId=24(二级类目ID), serviceId=37(一级类目ID)
			const [serviceId, groupId] = selectedTab.id.split('-');
			state.currentServiceId = Number(serviceId); // 一级类目ID
			state.currentGroupId = Number(groupId); // 二级类目ID
			// 切换标签后立即刷新数据
			reload();
		}
	};

	const queryList = async (pageNum, pageSize) => {
		try {
			const params = {
				pageNum: pageNum,
				pageSize,
				areaId: state.currentAreaId || getAreaid()
			};

			if (state.itemIds.length > 0) {
				params.itemIds = state.itemIds.join(',');
			} else {
				// 修改参数顺序：groupId使用二级类目ID，serviceId使用一级类目ID
				params.groupId = state.currentGroupId; // 二级类目ID
				params.serviceId = state.currentServiceId; // 一级类目ID
			}
			if (props.itemIdsArr && props.itemIdsArr.length > 0) {
				params.itemIdsStr = props.itemIdsArr.join(',');
				// console.log('使用传入的itemIds参数请求:', params.itemIdsStr);
			}
			// console.log('调用接口的参数:', params);
			const res = await getSevItemList(params);

			if (Array.isArray(res.rows)) {
				pagingRef.value.complete(res.rows);
			} else {
				throw new Error('接口返回数据格式错误，rows不是数组');
			}
		} catch (error) {
			console.error('getSevItemList调用失败:', error.message);
			pagingRef.value.complete(false);
		}
	};

	const handleCategoryChange = (data) => {
		if (data?.ids && Array.isArray(data.ids)) {
			state.itemIds = data.ids;
			console.log('接收到的筛选ID:', state.itemIds);
			// 等待组件初始化完成后再刷新
			if (initialized.value && pagingRef.value) {
				pagingRef.value.reload();
			} else {
				// 若未初始化，延迟重试
				setTimeout(() => {
					if (pagingRef.value) pagingRef.value.reload();
				}, 300);
			}
		}
	};

	onMounted(() => {
		console.log('targetItemIdsStr.value', );
		uni.$off('areaSelected', handleAreaChange);
		uni.$on('areaSelected', handleAreaChange);

		uni.$off('categorySelected', handleCategoryChange);
		uni.$on('categorySelected', handleCategoryChange);

		setTimeout(() => {
			initialized.value = true;
		}, 100);
	});

	onUnmounted(() => {
		uni.$off('areaSelected', handleAreaChange);
		uni.$off('categorySelected', handleCategoryChange);
	});

	const reload = () => {
		// 添加防重复加载逻辑
		if (state.isReloading) return;
		state.isReloading = true;

		nextTick(() => {
			pagingRef.value?.reload();
			// 延迟重置标志，确保请求完成
			setTimeout(() => {
				state.isReloading = false;
			}, 500);
		});
	};

	// 暴露方法给父组件
	defineExpose({
		reload
	});

	const itemClick = (item) => {
		uni.navigateTo({
			url: `/pages/viewSonic/viewSonicDetail?id=${item.localId}`
		});
	};

	const openSelectService = () => {
		uni.navigateTo({
			url: "/pages/tabBars/selectService/selectService?eventName=categorySelected"
		});
	};
</script>

<style lang="scss" scoped>
	.content {
		padding-top: 14rpx;
		// height: 100%;
		height: calc(100vh - 360rpx);
		background: #fff;
	}

	.box_2_tabs {
		position: sticky;
		top: 0;
		z-index: 10;

		.selectMore {
			width: 80rpx;
			font-weight: 500;
			font-size: 28rpx;
			color: #666666;
			padding: 0 25rpx;

			.more_img {
				width: 16rpx;
				height: 16rpx;
				margin-top: 6rpx;
			}
		}
	}

	.item {
		background: #ffffff;
		box-shadow: 0px 5rpx 20rpx 0px #e2e8f0;
		border-radius: 20rpx;
		padding: 24rpx 23rpx;
		margin: 26rpx 24rpx 0;

		.left_img {
			width: 203rpx;
			height: 203rpx;
			margin-right: 21rpx;
			border-radius: 20rpx;
		}

		.title {
			font-weight: 500;
			font-size: 34rpx;
			font-weight: bold;
			color: #333333;
			line-height: 45rpx;
		}

		.desc {
			font-weight: 400;
			font-size: 26rpx;
			color: #999999;
			line-height: 33rpx;
			// margin-top: 15rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			overflow: hidden;
			text-overflow: ellipsis;
		}

		.price1 {
			font-size: 20rpx;
			color: #ff6a47;
		}

		.price2 {
			font-size: 32rpx;
			color: #ff6a47;
			font-weight: bold;
		}

		.text3 {
			font-weight: 400;
			font-size: 20rpx;
			color: #999999;
			line-height: 28rpx;
		}
		.uni-column{
			line-height: 53rpx;
		}
	}
</style>